package cn.com.yangzhenyu.brick.controller;

import cn.com.yangzhenyu.brick.example.CommonExample;
import cn.com.yangzhenyu.brick.exception.MySQLException;
import cn.com.yangzhenyu.brick.pojo.ApiResult;
import cn.com.yangzhenyu.brick.pojo.BaseData;
import cn.com.yangzhenyu.brick.service.TableService;
import cn.com.yangzhenyu.brick.util.FreemarkerUtils;
import cn.com.yangzhenyu.brick.util.TokenUtils;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 允许的跨域访问
 * Created with IntelliJ IDEA
 * Created By 杨振宇
 * Date: 2018/6/28
 * Time: 23:03
 */
@Controller
@RequestMapping("/function")
public class FunctionController {

    @Resource
    private TableService tableService;


    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index() throws MySQLException {
        ModelAndView mv = new ModelAndView("function");
        CommonExample example = new CommonExample("function");
        List<LinkedHashMap<String, Object>> list = tableService.findListData(example);
        mv.addObject("functionList", list);
        return mv;
    }

    @RequestMapping(value = "{action}")
    @ResponseBody
    public ApiResult get(@PathVariable(name = "action") String action, HttpServletRequest request) throws MySQLException {


        try {
//          验证
            String token = request.getHeader("Y-Token");
            String userId = request.getHeader("Y-User");

            if (StrUtil.hasBlank(token, userId)) return ApiResult.error(-999, "没有权限");
            if (!TokenUtils.isAuto(Integer.valueOf(userId), token)) return ApiResult.error(-888, "没有权限");

            CommonExample example = new CommonExample("function");
            CommonExample.Criteria criteria = example.createCriteria();
            criteria.andColumnEqualTo("name", action);
            LinkedHashMap<String, Object> function = tableService.findOneData(example);
            if (null == function) return ApiResult.error(-5, "没有找到对应方法");
            Map<String, Object> paramsMap = new HashMap<>();
            String dataStr = MapUtil.getStr(function, "data");
            String[] keys = dataStr.split(",");
            for (String key : keys) {
                if (key.equals("")) break;
                if ("userId".equals(key)) {
                    paramsMap.put(key, userId);
                } else {
                    String value = request.getParameter(key);
                    if (null == value) return ApiResult.error(-6, "参数不能为空");
                    paramsMap.put(key, value);
                }
            }
            String sql = MapUtil.getStr(function, "sql");
            sql = sql.replace("\\$", "$");
            if (!paramsMap.isEmpty()) sql = FreemarkerUtils.templateString(sql, paramsMap);
            // 记得删掉
            System.out.println(action + ":" + sql);
            return ApiResult.success("操作成功").data(tableService.executeSql(sql));

        } catch (Exception e) {
            return ApiResult.error(500, "服务器发生错误[" + e.getMessage() + "]");
        }
    }


    @RequestMapping("/create")
    @ResponseBody
    public ApiResult create(String name, String sql, String type, String data) throws MySQLException {
        if (StrUtil.hasBlank(name, sql)) {
            return ApiResult.error("请求参数不能为空..");
        }
        try {
            BaseData function = BaseData.createBaseData("function");
            function.putData("name", name);
            sql = sql.replace("$", "\\$");
            function.putData("sql", sql);
            function.putData("type", type);
            function.putData("data", data);
            return ApiResult.success("添加成功").data(tableService.addData(function));
        } catch (MySQLException e) {
            return ApiResult.error(e.getErrorCode(), e.getErrorMessage());
        } catch (Exception ex) {
            return ApiResult.error(500, "服务器发生错误[" + ex.getMessage() + "]");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ApiResult delete(String name) throws MySQLException {
        if (StrUtil.hasBlank(name)) {
            return ApiResult.error("请求参数不能为空..");
        }
        try {
            //{"where":{"name":"杨振宇"},"tableName":"test"}
            BaseData data = BaseData.createBaseData("function");
            data.putWhere("name", name);
            return ApiResult.success("删除成功").data(tableService.deleteData(data));
        } catch (MySQLException e) {
            return ApiResult.error(e.getErrorCode(), e.getErrorMessage());
        } catch (Exception ex) {
            return ApiResult.error(500, "服务器发生错误[" + ex.getMessage() + "]");
        }
    }

}
